<template>
    <view class="main-user bg-user">
        <view class="login shadow">
            <view class="pic"><text class="icon-people text-blue"></text></view>
            <view class="hint">用户登录</view>

            <view class="form-group margin-top">
                <view class="title">手机号：</view>
                <input placeholder="请输入手机号" maxlength="11" placeholder-class="phc" v-model="phone" type="number" />
            </view>

            <view class="form-group">
                <view class="title">密码：</view>
                <input placeholder="请输入密码" maxlength="30" type="password" placeholder-class="phc" v-model="pwd" />
            </view>
            <view class="form-group-pwd" @tap="bindRememberTap">
                <text :class="remember ? 'icon-squarecheckfill text-blue' : 'icon-square'"></text>
                记住密码
            </view>

            <button class="btn bg-blue margin-bottom" @tap="bindLoginTap">点击登录</button>
            <view class="return text-grey">还没有账号？<text class="text-blue" @tap="bindRegTap">立即注册</text></view>
            <view @tap="bindBackTap" class="return text-grey">
                <text class="icon-back"></text>
                返回首页
            </view>
        </view>

        <view class="foot-bottom">
            <cmpt-foot />
        </view>
    </view>
</template>

<script>
import cmptFoot from '@/cmpts/biz/foot/foot_cmpt';
import PassportBiz from '@/utils/comm/biz/passport_biz.js';
import pageHelper from '@/utils/helper/page_helper.js';
import cacheHelper from '@/utils/helper/cache_helper.js';
import { userLogin } from '@/api/api.js';

export default {
    components: {
        cmptFoot
    },
    data() {
        return {
            phone: '',
            pwd: '',
            remember: false,
            retUrl: '' // 登录成功后要跳转的页面
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // PassportBiz.clearToken();

        // 获取返回页面URL
        if (options && options.retUrl) {
            this.retUrl = decodeURIComponent(options.retUrl);
        }

        // 记住密码
        let pwd = cacheHelper.get('user-pwd');
        if (pwd) {
            this.setData({
                phone: pwd.phone,
                pwd: pwd.pwd,
                remember: true
            });
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    methods: {
        url: function (e) {
            pageHelper.url(e, this);
        },

        bindBackTap: function (e) {
            uni.reLaunch({
                url: pageHelper.fmtURLByPID('/pages/my/index/my_index')
            });
        },

        bindRegTap: function (e) {
            uni.navigateTo({
                url: pageHelper.fmtURLByPID('/pages/my/reg/my_reg')
            });
        },

        bindLoginTap: async function (e) {
            if (this.phone.length != 11) {
                uni.showToast({
                    title: '请输入正确的手机号',
                    icon: 'none'
                });
                return;
            }
            if (this.pwd.length < 6 || this.pwd.length > 30) {
                uni.showToast({
                    title: '密码长度应为6-30位',
                    icon: 'none'
                });
                return;
            }

            // 记住密码
            if (this.remember) {
                cacheHelper.set(
                    'user-pwd',
                    {
                        pwd: this.pwd,
                        phone: this.phone
                    },
                    2592000
                );
            } else {
                cacheHelper.remove('user-pwd');
            }
            
            // 直接处理登录逻辑，以便控制跳转
            let params = {
                phone: this.phone,
                password: this.pwd
            };
            let opt = {
                title: '登录中'
            };
            
            try {
                await userLogin(params, opt).then((res) => {
                    console.log('用户登录成功', res);
                    if (res && res.token && res.userInfo) {
                        // 设置用户token
                        PassportBiz.setToken({
                            id: res.userInfo.id,
                            name: res.userInfo.username,
                            status: res.userInfo.status || 1,
                            token: res.token,
                            avatar: res.userInfo.avatar
                        });
                        
                        uni.showToast({
                            title: '登录成功',
                            icon: 'success'
                        });
                        
                        setTimeout(() => {
                            // 根据retUrl决定跳转页面
                            if (this.retUrl) {
                                uni.redirectTo({
                                    url: this.retUrl,
                                    fail: () => {
                                        // 如果跳转失败，回到默认页面
                                        uni.reLaunch({
                                            url: pageHelper.fmtURLByPID('/pages/my/index/my_index')
                                        });
                                    }
                                });
                            } else {
                                uni.reLaunch({
                                    url: pageHelper.fmtURLByPID('/pages/my/index/my_index')
                                });
                            }
                        }, 1500);
                    } else {
                        uni.showToast({
                            title: '登录失败，请检查账号密码',
                            icon: 'none'
                        });
                    }
                });
            } catch (e) {
                console.log('用户登录失败', e);
                uni.showToast({
                    title: '登录失败，请重试',
                    icon: 'none'
                });
            }
        },

        bindRememberTap: function (e) {
            this.setData({
                remember: !this.remember
            });
        }
    }
};
</script>
<style>
@import './login.css';
</style>